//
// Created by lanlu on 2025/8/8.
//

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;

    TreeNode() : val(0), left(nullptr), right(nullptr){}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr){}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right){}
};

class Solution {
public:
    TreeNode* insertIntoBST(TreeNode* root, int val) {
        // 找到要插入节点的位置
        if (root == nullptr)
            return new TreeNode(val);
        if (root->val > val)
        {
            // 要放入左子树
            root->left = insertIntoBST(root->left, val);
        }
        else
        {
            // 要放入右子树
            root->right = insertIntoBST(root->right, val);
        }
        return root;
    }

};